package es.us.lsi.daw.soportePropiedades;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalendarEditor extends PropertyEditorSupport {

	private static DateFormat	FMT_FCH_H	= new SimpleDateFormat("dd/MM/yyyy hh:mm");
	private static DateFormat	FMT_FCH		= new SimpleDateFormat("dd/MM/yyyy");
	private static DateFormat	FMT_FCH2	= new SimpleDateFormat("dd-MM-yyyy");
	private static DateFormat	FMT_H		= new SimpleDateFormat("hh:mm");

	@Override
	public void setAsText(String text) throws IllegalArgumentException {

		try {
			if (!text.isEmpty()) {
				if (getValue() == null)
					setValue(GregorianCalendar.getInstance());
				((GregorianCalendar) getValue()).setTime(FMT_FCH.parse(text));

				Calendar calendario = Calendar.getInstance();
				if (text.contains("/") && text.contains(":")) {
					calendario.setTime(FMT_FCH_H.parse(text));
				} else if (text.contains("/")) {
					calendario.setTime(FMT_FCH.parse(text));
				} else if (text.contains(":")) {
					calendario.setTime(FMT_H.parse(text));
				} else if (text.matches("\\d\\d?-\\d\\d?-\\d\\d\\d\\d")) {
					calendario.setTime(FMT_FCH2.parse(text));
				}
				this.setValue(calendario);

			} else
				setValue(null);
		} catch (ParseException e) {
			setValue(null);
			e.printStackTrace();
		}
	}

	@Override
	public String getAsText() {

		try {
			if (this.getValue() != null) {
				return FMT_FCH.format(((GregorianCalendar) getValue()).getTime());
			}
			return "";
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

}
